﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Globalization;

namespace Pai.LiveStation.Web.Controllers
{
    public class MembersController : Controller
    {
        //
        // GET: /Members/

        public ActionResult Index()
        {
            return View();
        }

        [Authorize]
        public ActionResult Create()
        {
            return View();
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(string username, string password, 
            string firstName, string lastName, string email)
        {
            MembershipUser user = null;
            try
            {
                user = Membership.CreateUser(username, password, email);
            }
            catch (Exception e)
            {
                ModelState.AddModelError("_FORM", MembersHelper.ErrorCodeToString(MembershipCreateStatus.ProviderError));
            }

            if(user != null)
            using (Models.AuthenticationClassesDataContext dc = new Models.AuthenticationClassesDataContext())
            {
                Models.aspnet_User foundUser = dc.aspnet_Users.Where(u => u.UserId == (Guid)user.ProviderUserKey).FirstOrDefault();
                Models.MemberProfile profile = new Models.MemberProfile();
                profile.Name = firstName + " " + lastName;
                foundUser.MemberProfiles.Add(profile);

                dc.SubmitChanges();
            }

            return View();

        }

        [Authorize]
        public ActionResult ChangePassword()
        {

            //ViewData["PasswordLength"] = Provider.MinRequiredPasswordLength;

            return View();
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangePassword(string currentPassword, string newPassword)
        {
            // Basic parameter validation
            if (String.IsNullOrEmpty(currentPassword))
            {
                ModelState.AddModelError("currentPassword", "You must specify a current password.");
            }
            if (newPassword == null || newPassword.Length < Membership.MinRequiredPasswordLength)
            {
                ModelState.AddModelError("newPassword",
                    String.Format(CultureInfo.CurrentCulture,
                         "You must specify a new password of {0} or more characters.",
                         Membership.MinRequiredPasswordLength));
            }

            if (ModelState.IsValid)
            {
                bool changeSuccessful = false;
                try
                {
                    changeSuccessful = Membership.GetUser().ChangePassword(currentPassword, newPassword);
                }
                catch
                {
                }

                if (!changeSuccessful)
                {
                    ModelState.AddModelError("_FORM", "The current password is incorrect or the new password is invalid.");
                }
            }
            return View();
        }

        public ActionResult Login()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(string username, string password, bool rememberMe, string returnUrl)
        {
            // Basic parameter validation
            if (String.IsNullOrEmpty(username))
            {
                ModelState.AddModelError("username", "You must specify a username.");
            }
            if (String.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password", "You must specify a password.");
            }

            if (ViewData.ModelState.IsValid)
            {
                // Attempt to login
                bool loginSuccessful = Membership.ValidateUser(username, password);

                if (loginSuccessful)
                {
                    FormsAuthentication.SetAuthCookie(username, rememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("_FORM", "The username or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["rememberMe"] = rememberMe;
            return View();
        }

        public ActionResult View(string id)
        {
            Guid userID = new Guid(id);
            MembershipUser user = Membership.GetUser(userID);

            if (user == null)
            {
                ModelState.AddModelError("Error", "Cannot find user.");
                return View();
            }

            ViewData["Member"] = MembersHelper.GetProfile((Guid)user.ProviderUserKey);

            return View();
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }
      

    }
}
